import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
// import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    username: '',
    uid: '',
    role: '',
    avator: 'https://static.hdslb.com/images/akari.jpg'
  },
  getters: {},
  mutations: {
    // 登陆后保存用户名
    saveUname(state, uname) {
      state.username = uname
    },
    // 保存用户id
    saveUid(state, uid) {
      state.uid = uid
    },
    // 保存用户角色
    saveUrole(state, role) {
      state.role = role
    },
    // 保存用户头像
    saveAvator(state, avator) {
      state.avator = avator
    }
  },
  actions: {
    // 根据用户id获取用户信息
    async getUserInfo(store) {
      // 如果用户数据已经存在，则不用再获取
      if (store.state.username) return

      let uid = window.localStorage.getItem('uid')
      const { data: res } = await axios.get('/users/' + uid)
      if (res.meta.status !== 200) {
        return alert('获取用户信息失败，请重新登陆')
      }
      let { username, _id, role, avator } = res.data
      avator = 'http://127.0.0.1' + avator

      store.commit('saveUname', username)
      store.commit('saveUid', _id)
      store.commit('saveUrole', role)
      store.commit('saveAvator', avator)
    }
  },
  modules: {}
})
